package responseData.config;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.SneakyThrows;
import org.apache.logging.log4j.message.ObjectMessage;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import java.util.HashMap;

import static org.apache.logging.log4j.message.MapMessage.MapFormat.JSON;

/**
 * @Author quan
 * @Description 统一数据返回处理格式
 * @Date 2023/7/29 16:09
 */
@ControllerAdvice
public class ResponseHandler implements ResponseBodyAdvice {

    @Override
    public boolean supports(MethodParameter returnType, Class converterType) {
        return true;
    }

    @SneakyThrows//处理异常
    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        HashMap<String,Object> result = new HashMap<>();
        result.put("success",1);
        result.put("data",body);
        result.put("errMsg","");
        if (body instanceof String) {
            //解决返回值为字符串时，直接返回，不用包装
            ObjectMapper mapper = new ObjectMapper();
                return mapper.writeValueAsString(result);
        }
        return result;
    }
}
